/*
 * @(#)EntityTypeModel.java        0.1 05-Apr-2009
 *
 * Copyright 2008 Thomas Ford. All rights reserved.
 */


package edu.napier.soc.xfdm.uci;

import edu.napier.soc.xfdm.model.*;
import edu.napier.soc.xfdm.uci.EntityTypeModel.RelationshipModel.Cardinality;

import java.util.LinkedList;
import java.util.List;

/**
 * @author Thomas Ford
 * @version 0.1, 05-Apr-2009
 */
public class EntityTypeModel {

	private EntityType entityType;
	private List<String> functions;
	private List<String> constraints;
	private List<RelationshipModel> relationships;

	public EntityTypeModel() {
	}

	public EntityTypeModel(EntityType entityType) {
		this.entityType = entityType;
		functions = new LinkedList<String>();
		constraints = new LinkedList<String>();
		relationships = new LinkedList<RelationshipModel>();

		for (Function f : entityType.getFunctions()) {
			if (f.getReturnType() != ReturnType.ENTITY &&
					!entityType.isSupertypeFunction(f)) {
				functions.add(f.getName() + " - " + f.getReturnType());
			} else {
				Cardinality c = f.isMultiValued()
						? Cardinality.ONETOMANY : Cardinality.ONETOONE;
				relationships.add(
						new RelationshipModel(
								((EntityFunction) f).getEntityType(), c, f));
			}
		}

		if (entityType.getSupertype() != null) {
			relationships.add(new RelationshipModel(entityType.getSupertype(),
					Cardinality.SUPERTYPE, null));
		}

		for (Constraint c : entityType.getConstraints()) {
			constraints.add(c.getName() + " - " + c.getConstraintType());
		}
	}

	public EntityType getEntityType() {
		return entityType;
	}

	public void setEntityType(EntityType entityType) {
		this.entityType = entityType;
	}

	public List<String> getFunctions() {
		return new LinkedList<String>(functions);
	}

	public List<String> getConstraints() {
		return new LinkedList<String>(constraints);
	}

	public List<RelationshipModel> getRelationships() {
		return new LinkedList<RelationshipModel>(relationships);
	}

	public static class RelationshipModel {

		public enum Cardinality {
			ONETOONE("1:1"), ONETOMANY("1:N"), SUPERTYPE("inherits");
			private final String name;

			Cardinality(String name) {
				this.name = name;
			}

			public String getName() {
				return name;
			}
		}

		private final EntityType e;
		private final Cardinality c;
		private final Function f;

		public RelationshipModel(EntityType e, Cardinality c, Function f) {
			this.e = e;
			this.c = c;
			this.f = f;
		}

		public EntityType getRelationshipTo() {
			return e;
		}

		public Cardinality getCardinality() {
			return c;
		}

		public Function getFunction() {
			return f;
		}
	}
}
